import 'package:ai_desktop_eidtor/models/hive_models.dart';
import 'package:ai_desktop_eidtor/util/y_req.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';

import 'editor_state.dart';

class EditorLogic extends GetxController {
  final EditorState state = EditorState();
  TextEditingController input = TextEditingController();
  TextEditingController chapterField = TextEditingController();
  var isFold = true.obs;
  var currentChapterIndex = 0.obs;
  var length = 0.obs;
  List<ChapterModel> chapters = [];

  String bookId = '';
  String title = '';

  @override
  void onReady() {
    // TODO: implement onReady
    bookId = Get.arguments['bookId'];
    title = Get.arguments['title'];
    update();
    super.onReady();
    input.addListener(_handleAutoIndent);
    loadChapter();
  }

  void loadChapter() {
    yGet(
      load: (res) async {
        chapters = await res.getChaptersByBook(bookId);
        if(chapters.isNotEmpty){
          currentChapterIndex.value = chapters.length - 1;
          chapterField.text = chapters.last.title;
          input.text = chapters.last.content;
          getTextLength();
          update();
        }
      },
    );
  }

  void addChapter({bool isAdd = true}) {
    yPost(
      load: (res) async{
       await res.addChapter(
          ChapterModel(
            id: '${bookId}_chapterId_${chapters.length + 1}',
            bookId: bookId,
            title: isAdd ? '' : chapterField.text,
            content: isAdd ? '' : input.text,
            chapterNumber: chapters.length + 1,
          ),
        );
       loadChapter();
      },
    );
  }

  void saveChapter({Function()? okBlock}) async{
    if(chapters.isEmpty){
      addChapter(isAdd: false);
      return;
    }
    if(chapterField.text.isEmpty && input.text.isEmpty){
      return;
    }
    ChapterModel cm = chapters[currentChapterIndex.value];
    cm.content = input.text;
    if(chapterField.text.isNotEmpty){
      cm.title = chapterField.text;
    }
    cm.updatedAt = DateTime.now();
    cm.chapterNumber = currentChapterIndex.value + 1;
    yPost(load: (res) async{
      await res.updateChapter('${bookId}_chapterId_${currentChapterIndex.value + 1}', cm);
      update();
      if(okBlock != null){
        okBlock();
      }

    });
  }


  void openOrFold() {
    isFold.value = !isFold.value;
  }

  void switchChapterIndex(int index) {
    currentChapterIndex.value = index;
    chapterField.text = chapters[index].title;
    input.text = chapters[index].content;
    getTextLength();
    update();
  }

  void getTextLength() {
    length.value = input.text.replaceAll('\n', '').replaceAll(' ', '').length;
  }





  ///自动换行 缩进处理
  void _handleAutoIndent() {
    final text = input.text;
    final selection = input.selection;

    // 如果文本为空或没有选择，直接返回
    if (text.isEmpty || !selection.isValid) return;

    // 检查是否在行首按了回车
    if (_isAtLineStart(text, selection) && _isNewLineInput(text, selection)) {
      _insertIndent();
    }
  }
  bool _isAtLineStart(String text, TextSelection selection) {
    if (selection.baseOffset == 0) return true;

    // 检查光标前是否是换行符
    final beforeCursor = text.substring(0, selection.baseOffset);
    return beforeCursor.endsWith('\n');
  }

  bool _isNewLineInput(String text, TextSelection selection) {
    // 检查是否刚刚输入了换行符
    return selection.baseOffset > 0 &&
        text.length >= selection.baseOffset &&
        text.codeUnitAt(selection.baseOffset - 1) == 10; // 10是\n的ASCII码
  }

  void _insertIndent() {
    final text = input.text;
    final selection = input.selection;

    // 获取上一行的缩进
    final lines = text.split('\n');
    if (lines.length >= 2) {
      final previousLine = lines[lines.length - 2];
      // final baseIndent = _calculateIndent(previousLine);
      // 插入缩进
      final indent = ' ' * state.indentSpaces;
      final newText = text.substring(0, selection.baseOffset) +
          indent +
          text.substring(selection.baseOffset);

      input.value = input.value.copyWith(
        text: newText,
        selection: TextSelection.collapsed(
          offset: selection.baseOffset + indent.length,
        ),
      );
    } else {
      // 第一行，只插入基础缩进
      final indent = ' ' * state.indentSpaces;
      final newText = text.substring(0, selection.baseOffset) +
          indent +
          text.substring(selection.baseOffset);

      input.value = input.value.copyWith(
        text: newText,
        selection: TextSelection.collapsed(
          offset: selection.baseOffset + indent.length,
        ),
      );
    }
  }

  int _calculateIndent(String line) {
    // 计算行的缩进空格数
    int count = 0;
    for (int i = 0; i < line.length; i++) {
      if (line[i] == ' ') {
        count++;
      } else {
        break;
      }
    }
    return count;
  }
}
